package com.rfid.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileUtil {


    public static void streamToFile(InputStream in, File out) throws IOException {
        FileOutputStream fos = new FileOutputStream(out);
        byte buffer[] = new byte[8012];
        int len = 0;
        while((len = in.read(buffer)) != -1) {
            fos.write(buffer,0,len);
        }
        fos.flush();
        fos.close();
    }

    public static String readFile(String path) {
        try {
            FileInputStream fin = new FileInputStream(path);
            BufferedReader br = new BufferedReader(new InputStreamReader(fin));
            StringBuffer sb = new StringBuffer();
            String s = null;
            while((s = br.readLine()) != null) {
                sb.append(s);
            }
            br.close();
            return sb.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void writeFile(String path,String text) {
        try {
            FileOutputStream fos = new FileOutputStream(path);
            fos.write(text.getBytes());
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void rm(String path) {
        File file = new File(path);
        if (file.exists()) {
            if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (File f : files) {
                    rm(f.getPath());
                }
                file.delete();
            } else {
                file.delete();
            }
        }
    }

    public static void mv(String from,String to) {
        File toFile = new File(to);
        if(toFile.exists()) {
            toFile.delete();
        }
        File file = new File(from);
        file.renameTo(toFile);
    }
}
